﻿
var isIE = (document.all) ? true : false;

var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
};

Object.extend = function(destination, source) {
	for (var property in source) destination[property] = source[property];
	return destination;
};

Function.prototype.bind = function(object){
	var __method = this;
	return function(){
		return __method.apply(object,arguments);
	}
};

if (!Array.prototype.forEach){
	Array.prototype.forEach = function(fn, bind){
		for(var i = 0; i < this.length ; i++) fn.call(bind, this[i], i);
	};
}

Array.prototype.each = Array.prototype.forEach;

String.prototype.camelize = function(){
	return this.replace(/-\D/gi, function(match){
		return match.charAt(match.length - 1).toUpperCase();
	});
};

var $A = function(iterable) {
	var nArray = [];
	for (var i = 0; i < iterable.length; i++) nArray.push(iterable[i]);
	return nArray;
};

if (!window.Element) var Element = {};

Object.extend(Element, {

	remove: function(element) {
		element = $(element);
		element.parentNode.removeChild(element);
	},

	hasClassName: function(element, className) {
		element = $(element);
		return !!element.className.match(new RegExp("\\b"+className+"\\b"));
	},

	addClassName: function(element, className) {
		element = $(element);
		if (!Element.hasClassName(element, className)) element.className = (element.className+' '+className);
	},

	removeClassName: function(element, className) {
		element = $(element);
		if (Element.hasClassName(element, className)) element.className = element.className.replace(className, '');
	}

});

Object.extend(Object.prototype,{
	getRect: function(){
		var rect = {};
		rect.left = this.getBoundingClientRect().left + document.documentElement.scrollLeft;
		rect.right = this.getBoundingClientRect().right + document.documentElement.scrollLeft;
		rect.top = this.getBoundingClientRect().top + document.documentElement.scrollTop;
		rect.bottom = this.getBoundingClientRect().bottom + document.documentElement.scrollTop;
		rect.width = this.getBoundingClientRect().right - this.getBoundingClientRect().left;
		rect.height = this.getBoundingClientRect().bottom - this.getBoundingClientRect().top;
		return rect;
	}
});

document.getElementsByClassName = function(className){
	var elements = [];
	var all = document.getElementsByTagName('*');
	$A(all).each(function(el){
		if (Element.hasClassName(el, className)) elements.push(el);
	});
	return elements;
};

function $(element) {
	if (arguments.length > 1) {
		for (var i = 0, elements = [], length = arguments.length; i < length; i++){
			elements.push($(arguments[i]));
		}
		return elements;
	}
	if (element.constructor == String){
		element = document.getElementById(element);
		return element;
	}
}

function $$(rule){ //$$('#id .hide[type="text"]')
	var rule = rule.split(' ');
	var str = '';
	var arr = [];
	for(var i = 0, len = rule.length; i < len; i++){
		if(/#/.test(rule[i])){
			var id = rule[i].replace('#','')
			arr.push('getElementById('+id+')');
		}
		if(/\./.test(rule[i])){
			arr.push('getElementsByClassName('+rule[i]+')');
		}
	}
}

var Ajax = {
	Request: function(url,options){
		var xmlHttp = false;
		try{
			xmlHttp = new XMLHttpRequest();
		}catch(e){
			try{
				xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
			}catch(e2){
				xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
			}
		}
		
		var config = {
			method:'GET',
			asyn:true,
			parameter:null,
			onSuccess: function(){},
			onError: function(){}
		};
		if(options != 'undefined'){
			Object.extend(config,options);
		}
		//console.info(xmlHttp.onreadystatechange);
		xmlHttp.onreadystatechange = (document.all) ? handler : handler();
		function handler(){
			if(xmlHttp.readyState  == 4){
				if(xmlHttp.status == 200){
					config.onSuccess(xmlHttp);
				}else{
					config.onError();
				}
			}
		};
		//if(config.method == 'POST') xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlHttp.open(config.method,url,config.asyn);
		
		//var parameter = config.method == 'GET' ? null : config.parameter;
		xmlHttp.send(parameter);
		xmlHttp.onreadystatechange = (document.all) ? handler : handler();
	}
};

//表单验证类

var ValidateForm = Class.create();

ValidateForm.prototype = {
	initialize:function(formId, valiRules, preFun) {
		this.idForm = formId;
		this.illegalArr = [];
		this.ruleList = { //过滤规则表
			noEmpty : "_o.value == ''",
			isEmail: "_o.value != '' && !/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(_o.value)",
			isIp: "_o.value != '' && !/^(((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))\\.){3}((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))$/.test(_o.value)",
			isMac: "_o.value != '' && !/^([0-9a-fA-F]{2})(([/\\s:-][0-9a-fA-F]{2}){5})$/.test(_o.value)",
			isPort: "_o.value !='' && (!/^[0-9]*[1-9][0-9]*$/.test(_o.value) || _o.value < 0 || _o.value > 65535)",
			isIpRange: "_o.value !='' && !(/^(((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))\\.){3}((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))$/.test(_o.value) || /^(((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))\\.){3}((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))\\/([0-9]|1[0-9]|2[0-9]|3[0-2])$/.test(_o.value) || /^(((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))\\.){3}((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))-(((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))\\.){3}((\\d{1})|(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})|(25[0-5]))$/.test(_o.value))",
			isInt: "_o.value !='' && !/^[0-9]*[1-9][0-9]*$/.test(_o.value)"
		};
		this.valiRules = valiRules;
		this.preFun = preFun ? preFun : function(){};

		//this.options = options? options : [];
		$(formId).onsubmit = this.validate.bind(this);
	},
	/* 规则处理 */
	collect: function(str){
		if(str != ''){
			var arr = [];
			var o = $$('#'+this.idForm+' .'+str)
			for(var i = o.length - 1; i >= 0; i--){
				var rules = this.ruleList[str].replace(/_o/g,'o[i]');
				if(eval('('+rules+')')){
					arr.push(o[i]);
				}
			}
		}
		return arr;
	},

	/* 收集未通过验证的表单元素和错误消息 */
	validate: function() {
		   
		if(!this.valiRules || this.valiRules.length < 1) return;
	   
		$$('#'+this.idForm+' input').each(function(node){
			node.value = node.value.replace(/(^\s*)|(\s*$)/g,"");   //清除前后空格
		});
	   
		$$('#'+this.idForm+' textarea').each(function(node){
			node.value = node.value.replace(/(^\s*)|(\s*$)/g,"");                                                   
		});
	   
		for(var i = 0; i < this.valiRules.length; i++){
			var result = this.collect(this.valiRules[i]);
			if(result){
				this.illegalArr = this.illegalArr.concat(result);
			}
		}

		for(var i = this.illegalArr.length - 1; i >= 0; i--){
			if(this.illegalArr[i].disabled || this.illegalArr[i].display == 'none'){
				this.illegalArr.splice(i,1);
			}	
		}
		return this.throwErr();
	},

	/* 抛出异常表单元素及消息 */
	throwErr: function() {
		var len = this.illegalArr.length;
		this.preFun();
		if(len > 0){
			for(var i = 0; i < len; i++){
				//this.illegalArr[i].style.backgroundColor = "#e42495";
				if(this.illegalArr[i].className.indexOf('error') < 0) this.illegalArr[i].addClassName('error');
				this.illegalArr[i].onfocus = clear;
			}

			this.illegalArr = [];
			return false;
		}
		return true;
	}
};


/* 清除错误提示 */
function clear(){
	this.className = this.className.replace("error","");
}
